<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入活动标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始日期" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上下线状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择上下线状态" clearable>
          <el-option
            v-for="dict in statusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['promotion:promotion:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['promotion:promotion:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['promotion:promotion:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['promotion:promotion:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="promotionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="活动标题" align="center" prop="title" />
      <el-table-column label="开始日期" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上下线状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status==1">上线</span>
          <span v-if="scope.row.status==0">下线</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['promotion:promotion:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="addShopPromotion(scope.row)"
            v-hasPermi="['shopKill:shopKill:edit']"
          >添加活动商品</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['promotion:promotion:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="开始日期" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上下线状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusList"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
        <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--添加活动商品对话框-->
    <el-dialog
      title="添加活动商品"
      :visible.sync="addShopPromotionStatus"
      width="500px">
      <el-form :inline="true" :model="shopPromotionInfo" class="demo-form-inline">
        <el-form-item label="商品">
          <el-select v-model="shopPromotionInfo.shopId" placeholder="商品" @change="changeShop(shopPromotionInfo.shopId)">
            <el-option v-for="shop in shopList" :label="shop.name" :value="shop.id" :key="shop.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图⽚" prop="shopImage">
          <el-image :src="shopPromotionInfo.shopImage"></el-image>
        </el-form-item>
        <el-form-item label="原价格" prop="shopPrice">
          <el-input readonly v-model="shopPromotionInfo.shopPrice"></el-input>
        </el-form-item>
        <el-form-item label="秒杀价格" prop="seckillPrice">
          <el-input-number v-model="shopPromotionInfo.seckillPrice" :precision="2" :step="0.1" ></el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="shopStock">
          <el-input readonly v-model="shopPromotionInfo.shopStock"></el-input>
        </el-form-item>
        <el-form-item label="秒杀总量" prop="name">
          <el-input-number v-model="shopPromotionInfo.seckillCount"  :min="1" :max="shopPromotionInfo.shopStock" label="秒杀总量"></el-input-number>
        </el-form-item>
        <el-form-item label="每人限购数量" prop="name">
          <el-input-number v-model="shopPromotionInfo.seckillLimit" :precision="2" :step="1.0" ></el-input-number>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="shopPromotionInfo.killDate" ></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="秒杀的这个日期的时间范围">
          <el-select v-model="shopPromotionInfo.timeScope" placeholder="时间范围" >
            <el-option v-for="timeScope in timeScopeList" :label="timeScope" :value="timeScope" :key="timeScope"></el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="addSHopPromotionButton()">添加秒杀</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listPromotion, getPromotion, delPromotion, addPromotion, updatePromotion } from "@/api/promotion/promotion";
import {selectShopByUp} from "@/api/shop/shop"
import {addkillShop} from "@/api/shopKill/shopKill"
export default {
  name: "Promotion",
  dicts: ['sys_common_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动表格数据
      promotionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        startTime: null,
        endTime: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      statusList: [
        {value: 0, label: '下线'},
        {value: 1, label: '上线'},
      ],
      addShopPromotionStatus: false,
      // 添加秒杀商品的对象
      shopPromotionInfo: {},
      // 所有状态为上线状态的商品
      shopList: [],
      timeScopeList: [
        '0-2','2-4','4-6','6-8','8-10','10-12','12-14','14-16','16-18','18-20','20-22','22-24'
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //添加活动商品
    addShopPromotion(promotion) {
      if(promotion.id == null) {
        this.$message.error("系统出错")
        this.getList()
        return
      }
      //获取活动详情
      getPromotion(promotion.id).then(response => {
        if(response.data.status == 0) {
          alert("该活动已下线")
          return
        }
        //查询所有商品 状态为上线
        selectShopByUp(1).then(response => {
          this.shopList = response.data
        })
        this.shopPromotionInfo.promotionId = promotion.id
        this.addShopPromotionStatus = true
      })
    },
    // 改变秒杀商品
    changeShop(shopId) {
      this.shopList.forEach(shop => {
        if(shopId == shop.id) {
          this.shopPromotionInfo.shopImage = shop.image
          this.shopPromotionInfo.shopPrice = shop.price
          this.shopPromotionInfo.shopStock = shop.stock
        }
      })
    },
    // 添加商品秒杀按钮
    addSHopPromotionButton() {
      addkillShop(this.shopPromotionInfo).then(response => {
          if(response.code != 200) {
              this.$message.error(response.msg)
          }
          this.$message.success(response.msg)
        this.addShopPromotionStatus = false
      })
    },
    /** 查询活动列表 */
    getList() {
      this.loading = true;
      listPromotion(this.queryParams).then(response => {
        this.promotionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        startTime: null,
        endTime: null,
        status: 0,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPromotion(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改活动";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePromotion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPromotion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除活动编号为"' + ids + '"的数据项？').then(function() {
        return delPromotion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('promotion/promotion/export', {
        ...this.queryParams
      }, `promotion_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
